package com.my.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.my.bean.HomeUser;
import com.my.bean.MoenyDetailed;
import com.my.bean.Room;
import com.my.bean.User;
import com.my.service.HomeUserService;
import com.my.service.MoenyDetailedService;
import com.my.service.OrderVipService;
import com.my.service.RoomService;
import com.my.util.SessionUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.*;

/**
 * <p>
 * 房间 前端控制器
 * </p>
 *
 * @author 张子艺
 * @since 2018-08-30
 */
@Controller
@RequestMapping("/room")
public class RoomController {
    @Autowired
    RoomService roomService;
    @Autowired
    MoenyDetailedService moenyDetailedService;
    @Autowired
    OrderVipService orderVipService;

    @Autowired
    HomeUserService homeUserService;
    Logger logger=Logger.getLogger(RoomController.class);
    //跳转
    @RequestMapping("/main.html")
    public String main(HttpSession session, Model model){
        model.addAttribute("roleValue", SessionUtil.getSessionUser(session).getRoles().getRoleValue());

        return  "/Home/homeMain";
    }
    //子页面跳转
    @RequestMapping("/child.html")
    public String child(String homeId, Model model){
        model.addAttribute("homeId",homeId);
        return  "/Alert/home_info";
    }    //新增页面跳转
    @RequestMapping("/add.html")
    public String toAdd(){
        return  "/Alert/home_add";
    }

    @RequestMapping("/del.html")
    public String toDel(){
        return  "/Alert/home_del";
    }

    //查询所有房间信息
    @RequestMapping("/findAllRoom")
    @ResponseBody
    public List<Room> findProjectByHomeId(String param,HttpSession session){
        Map map=new HashMap<>();
        Long userId=SessionUtil.getSessionUser(session).getId();
        boolean admin=false;
        //如果事超级管理员  即可查看所有的房间  判断是否为超级管理员
        if(SessionUtil.getSessionUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")){
            admin=true;
        }
        // 带条件模糊查询
        if(param!=null&&param!=""){
            EntityWrapper ew=new EntityWrapper();
            //向解析器中反射实体
            ew.setEntity(new Room());
            //注入条件              模糊查询的方式枚举类  default是两边%
            ew.like("room_name",param, SqlLike.DEFAULT);
            return  roomService.selectList(ew);
        }
        Long areaid = ((User)session.getAttribute("user")).getAreaId();

        return roomService.selectHomeListBySerch(param,userId,admin,areaid);
    }

    //查询所有房间 带条件（房间管理）
    @RequestMapping("/findProjectByHomeName")
    @ResponseBody
    public List<Room> findProjectByHomeName(String data1,String data2,String param,HttpSession session){
        String[] data1Str={};
        String[] data2Str={};
        boolean admin=false;
        //如果事超级管理员  即可查看所有的房间  判断是否为超级管理员
        if(SessionUtil.getSessionUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")){
            admin=true;
        }

        Long userId=SessionUtil.getSessionUser(session).getId();

        if(data1!=null&&data1!=""){
            data1Str=data1.split(",");
        }else{
            data1Str=null;
        }
        if(data2!=null&&data2!=""){
            data2Str =data2.split(",");
        }else{
            data2Str=null;
        }
        if(data1!=null&&data1!=""||data2!=null&&data2!=""){
            Long areaid = ((User)session.getAttribute("user")).getAreaId();
            return  roomService.findProjectByHomeName(data1Str,data2Str,param,userId,admin,areaid);
        }else{
            Long areaid = ((User)session.getAttribute("user")).getAreaId();
            return   roomService.selectHomeListBySerch(param,userId,admin,areaid);

        }

    }


    //新增房间
    @RequestMapping("/insertHome")
    @ResponseBody
    public String insertHome( String param,Long userId,HttpSession session){
        Long areaid = ((User)session.getAttribute("user")).getAreaId();
        Room room= JSONObject.parseObject(param,Room.class);
        room.setRoomValue(UUID.randomUUID()+"");
        Map map=new HashMap<>();
        map.put("room_name",room.getName());
        map.put("areaid",areaid);
        if(roomService.selectByMap(map).size()>0){
            return "该房间名已存在，请重新添加";
        }else{
            //新增房间  关联登陆用户
            room.setAreaid(areaid);
            if(roomService.insert(room)){
                /*HomeUser homeUser=new HomeUser();
                homeUser.setUserId( userId);
                homeUser.setHomeId( room.getId());
                if(homeUserService.insert(homeUser)){
                    return   "true";
                }
            }
                }*/
                return "true";
            };
            return   "false";

        }

    }
    //修改
    @RequestMapping("/updateHomeState")
    @ResponseBody
    public String updateHomeState(  String param){
        Room room= JSONObject.parseObject(param,Room.class);
        if(roomService.updateById(room)){
            return  "修改成功";
        }else{
            return    "修改失败";
        }

    }
    //查询出该房间未退房的订单关联字典表的套餐
    @RequestMapping("/findAllMealNameByHomeId")
    @ResponseBody
    public List<Room> findAllMealNameByHomeId(  Long homeId){
        List<Room> list= roomService.findAllMealNameByHomeId(homeId);
        return list;
    }

    //查询出该房间未退房的所有交易明细
    @RequestMapping("/findAllMoneyByHomeId")
    @ResponseBody
    public Map  findAllMoneyByHomeId(  Long homeId){

        return   roomService.findAllMoneyByHomeId(homeId);
    }

    //退房
    @RequestMapping("/overHome")
    @ResponseBody
    public String  overHome(  Long homeId){
        try {
            return   roomService.overHome(homeId);
        } catch (SQLException e) {
            return "出现错误，退房失败";
        }

    }



    //补缴尾款
    @RequestMapping("/addMoney")
    @ResponseBody
    public String addMoney(  String param,Long homeId){
        //查询出 该房间 未退房的 订单  如果出现异常则说明该房间出现了两个订单
        Long orderId;
        try {
            orderId = roomService.findOrderIdByHomeId(homeId);
        }catch (Exception e){
            logger.info("出现错误，ID为"+homeId+"的房间有两个订单");
            return  "出现错误，该房间有两个订单，请联系管理员";
        }
        if(orderId==null||orderId==0){
            return  "该房间没有订单";
        }
        MoenyDetailed moenyDetailed= JSONObject.parseObject(param,MoenyDetailed.class);
        moenyDetailed.setCreateTime(new Date().getTime());
        moenyDetailed.setOrderId(orderId);
        if(moenyDetailedService.insert(moenyDetailed)){
            return  "补缴成功";
        }else{
            return    "补缴成功";
        }

    }
    //查询所有 还未下订单的房间
    @RequestMapping("/findRoomByNoOrder")
    @ResponseBody
    public List<Room> findRoomByNoOrder(  String param,Long homeId,HttpSession session){
        boolean admin=false;
        //如果事超级管理员  即可查看所有的房间  判断是否为超级管理员
        if(SessionUtil.getSessionUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")){
            admin=true;
        }
        Long userId=SessionUtil.getSessionUser(session).getId();
        Long areaId=SessionUtil.getSessionUser(session).getAreaId();

        return  roomService.findRoomByNoOrder(userId,admin,areaId);
    }




    /**
     * 删除房间
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Long id){
        if(roomService.deleteById(id)){
            return "true";
        }else {
            return "false";
        }

    }




}
